package cn.liangcaomei.vod.controller;

import cn.liangcaomei.commonutils.R;
import cn.liangcaomei.servicebase.exceptionhandler.CustException;
import cn.liangcaomei.vod.service.VodService;
import cn.liangcaomei.vod.utils.ConstantVodUtils;
import cn.liangcaomei.vod.utils.InitVodClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    //注入服务
    @Autowired
    private VodService vodService;

    //上传视频到阿里云
    @PostMapping("uploadALiyVideo")
    public R uploadALiyVideo(MultipartFile file) {
        String videoId = vodService.uploadALiyVideo(file);
        return R.ok().data("videoId", videoId);
    }

    //根据视频id，删除阿里云中的视频
    @DeleteMapping("removeALiyVideo/{videoId}")
    public R removeALiyVideo(@PathVariable String videoId) {
        try {
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);

            //创建一个删除视频的 request 对象
            DeleteVideoRequest request = new DeleteVideoRequest();

            //向 request 对象设置视频id值
            request.setVideoIds(videoId);

            //调用初始化对象的方法
            client.getAcsResponse(request);

            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustException(20001, "删除阿里云视频失败");

        }

    }

    //删除多个阿里云视频的方法
    //参数多个视频id List videoIdList
    @DeleteMapping("delete-batch")
    public R deleteBatch(@RequestParam("videoIdList") List videoIdList) {
        vodService.removeMoreAlyVideo(videoIdList);
        return R.ok();
    }

    //根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        try {
            //创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建获取凭证 request & response 对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();

            //向 request 设置id
            request.setVideoId(id);

            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustException(20001,"获取视频凭证失败！");
        }
    }

}
